package com.gec.it.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.util.List;

@Component
public class EmailUtil {
    @Autowired
    private JavaMailSenderImpl mailSender;
    public void  sendMail(String to,String subject,String content){
        SimpleMailMessage m=new SimpleMailMessage();
        m.setFrom(mailSender.getUsername());//发送人
        m.setTo(to);
        m.setSubject(subject);
        m.setText(content);
        mailSender.send(m);
        System.out.println(m);
    }
    public void  sendMail(String to, String subject, String content, List<String> filepath) throws MessagingException {
        try {
            MimeMessage mm = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mm, true, "UTF-8");
            helper.setFrom(mailSender.getUsername());
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            if (filepath != null) {
                for (String f : filepath) {
                    File file = new File(f);
                    helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
                }
            }
            mailSender.send(mm);
            System.out.println("邮件发送完毕");
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

}
